from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView

from main.forms import QuestionForm, AnswerForm, TopicForm
from main.models import Question, Topic

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

# Create your views here.





def home(request):
    questions = Question.objects.all().order_by('-created_at')

    # 实例化分页器：每页显示 5 条数据（可根据需求调整数量）
    paginator = Paginator(questions, 5)

    # 获取前端传递的页码参数（默认从 1 开始）
    page = request.GET.get('page')

    try:
        # 获取指定页码的分页数据
        page_questions = paginator.page(page)
    except PageNotAnInteger:
        # 若页码不是整数，返回第 1 页
        page_questions = paginator.page(1)
    except EmptyPage:
        # 若页码超出范围，返回最后一页
        page_questions = paginator.page(paginator.num_pages)

    # 将分页后的对象传递给模板
    return render(
        request,
        'main/home.html',
        context={
            'questions': page_questions,  # 分页后的当前页数据
            'is_paginated': paginator.num_pages > 1,  # 只有当页数大于1时才显示分页控件
            'page_obj': page_questions,  # 分页对象（包含当前页、总页数等信息）
            'paginator': paginator  # 分页器对象（可选，模板中可通过 page_obj.paginator 访问）
        }
    )



    # return render(request, 'main/home.html', {'questions': questions})



@login_required
def create_question(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.author = request.user
            question.save()
            return redirect('main:home')
    else:
        form = QuestionForm()
    return render(request, 'main/create_question.html', {'form': form})

def question_detail(request, pk):
    question = get_object_or_404(Question, pk=pk)
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.question = question
            answer.author = request.user
            answer.save()
            return redirect('main:question_detail', pk=pk)
    else:
        form = AnswerForm()
    return render(request, 'main/question_detail.html', {'question': question, 'form': form})

def topic_list(request):
    topics = Topic.objects.all()
    return render(request, 'main/topic_list.html', {'topics': topics})

def topic_detail(request, pk):
    topic = get_object_or_404(Topic, pk=pk)
    questions = Question.objects.filter(topic=topic)
    return render(request, 'main/topic_detail.html', {'topic': topic, 'questions': questions})

@login_required
def create_topic(request):
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            topic = form.save()
            return redirect('main:topic_list')
    else:
        form = TopicForm()
    return render(request, 'main/create_topic.html', {'form': form})





